package com.youmans.eduservice.controller.front;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youmans.commonutils.JwtUtils;
import com.youmans.commonutils.R;
import com.youmans.commonutils.orderVo.CourseWebVoOrder;
import com.youmans.eduservice.client.OrderClient;
import com.youmans.eduservice.entity.EduCourse;
import com.youmans.eduservice.entity.chapter.ChapterVo;
import com.youmans.eduservice.entity.frontVo.CourseFrontVo;
import com.youmans.eduservice.entity.frontVo.CourseWebVo;
import com.youmans.eduservice.service.EduChapterService;
import com.youmans.eduservice.service.EduCourseService;
import com.youmans.servicebase.exceptionHandler.GuliException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/courseFront")
public class CourseFrontController {

    @Autowired
    private EduCourseService eduCourseService ;

    @Autowired
    private EduChapterService chapterService ;

    @Autowired
    private OrderClient orderClient ;

    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page, @PathVariable long limit, @RequestBody(required = false) CourseFrontVo courseFrontVo){
        Page<EduCourse> coursePage = new Page<>(page,limit);
        Map<String,Object> map = eduCourseService.getCourseFrontList(coursePage,courseFrontVo) ;
        return R.ok().data(map);
    }
    @ApiOperation("根据课程id查询课程基本信息")
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){
        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(courseId);

        List<ChapterVo> chapterVoList = chapterService.getChapterByCourseId(courseId);

        //        调用jwt工具类，根据request对象获取头信息，返回用户id
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(StringUtils.isEmpty(memberId)){
            throw new GuliException(20001,"您好，请登录再观看");
        }
        boolean buyCourse = orderClient.isBuyCourse(courseId,memberId);


        return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVoList).data("isBuy",buyCourse) ;
    }

    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String id){
        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder() ;
        BeanUtils.copyProperties(courseWebVo,courseWebVoOrder);
        return courseWebVoOrder ;
    }
}
